package com.peakmain.homemodule.activity;

import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.andview.refreshview.XRefreshView;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.peakmain.baselibrary.adapter.BaseFlowAdapter;
import com.peakmain.baselibrary.recyclerview.listener.OnItemClickListener;
import com.peakmain.baselibrary.utils.PreferencesUtil;
import com.peakmain.baselibrary.widget.FlowLayout;
import com.peakmain.homemodule.R;
import com.peakmain.homemodule.R2;
import com.peakmain.homemodule.adapter.HotKeyAdapter;
import com.peakmain.homemodule.adapter.SearchResultAdapter;
import com.peakmain.homemodule.base.BaseHomeActivity;
import com.peakmain.homemodule.contarct.HotkeyContract;
import com.peakmain.homemodule.presenter.HotKeyPresenter;
import com.peakmain.wanandroid.netmodule.bean.home.HotkeyBean;
import com.peakmain.wanandroid.netmodule.bean.home.SearchResultBean;
import com.peakmain.wanandroid.netmodule.utils.XRefreshUtils;

import java.util.LinkedHashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * author: peakmain
 * createdata：2019/7/23
 * mail: 2726449200@qq.com
 * desiption:
 */
public class SearchActivity extends BaseHomeActivity<HotKeyPresenter> implements HotkeyContract.View {
    @BindView(R2.id.recycler_view)
    public RecyclerView mRecyclerView;
    @BindView(R2.id.et_search)
    public EditText mEtSearch;
    @BindView(R2.id.xrefreshview)
    public XRefreshView mXrefreshView;
    @BindView(R2.id.ll_history)
    public LinearLayout mLlHistory;
    @BindView(R2.id.flow_layout)
    public FlowLayout mFlowLayout;
    @BindView(R2.id.tv_hot)
    public TextView mTvHot;
    private HotKeyAdapter mAdapter;
    private SearchResultAdapter mResultAdapter;
    private int page = 0;
    private int totalPage = 1;
    //频繁的插入，删除 历史记录
    private LinkedHashMap<String, String> mHistoryMap = new LinkedHashMap<>();

    @Override
    protected int getLayoutId() {
        return R.layout.activity_search;
    }

    @Override
    protected void initInjector() {
        mActivityComponent.inject(this);
    }

    @Override
    protected void initView() {

        initHistoryData();

        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setHasFixedSize(true);
        XRefreshUtils.getInstance().initXRefresh(mXrefreshView, this);
        //键盘搜索按钮事件
        mRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        mEtSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    String history = mEtSearch.getText().toString();
                    if (!TextUtils.isEmpty(history)) {
                        if (!mHistoryMap.containsKey(history)) {
                            mHistoryMap.put(history, history);
                            PreferencesUtil.getInstance().saveParam("HistoryHashMap", mHistoryMap);
                            initHistoryData();
                        }
                        getSearchResult();
                    }
                    KeyboardUtils.hideSoftInput(SearchActivity.this);
                }
                return false;//返回true，保留软键盘。false，隐藏软键盘
            }
        });
        mPresenter.getHotkeySearch();
        mXrefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh(boolean isPullDown) {
                getList(true, false);
            }

            @Override
            public void onLoadMore(boolean isSilence) {
                getList(false, true);
            }
        });
    }

    private void initHistoryData() {
        mHistoryMap = (LinkedHashMap<String, String>) PreferencesUtil.getInstance().getObject("HistoryHashMap");
        if (mHistoryMap == null || mHistoryMap.size() == 0) {
            mHistoryMap = new LinkedHashMap<>();
            mLlHistory.setVisibility(View.GONE);
        } else {
            mLlHistory.setVisibility(View.VISIBLE);
            for (String key : mHistoryMap.keySet()) {
                final String value = mHistoryMap.get(key);

                mFlowLayout.setAdapter(new BaseFlowAdapter() {
                    @Override
                    public int getCount() {
                        return mHistoryMap.size();
                    }

                    @Override
                    public View getView(int position, ViewGroup parent) {
                        TextView tagTv = (TextView) LayoutInflater.from(SearchActivity.this).inflate(R.layout.item_history_layout, parent, false);
                        tagTv.setText(value);
                        tagTv.setPadding(15, 5, 15, 5);
                        tagTv.setTextColor(ContextCompat.getColor(SearchActivity.this, R.color.color_9));

                        tagTv.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mEtSearch.setText(value);
                                mEtSearch.setSelection(value.length());
                                KeyboardUtils.hideSoftInput(SearchActivity.this);
                                getSearchResult();
                            }
                        });
                        return tagTv;
                    }
                });

            }
        }

    }



    private void getList(boolean isPullDown, boolean isSilence) {
        if (isPullDown) {
            page = 0;
        }
        if (isSilence) {
            if (page > totalPage) {
                return;
            }
        }
        String key = mEtSearch.getText().toString();
        if (!TextUtils.isEmpty(key)) {
            mPresenter.getSearchResult(page, key, isPullDown, isSilence);
        } else {
            ToastUtils.showShort("关键词不能为空");
        }
        mXrefreshView.stopRefresh();
        mXrefreshView.stopLoadMore();
    }

    @Override
    public void showHotKeySuccess(final List<HotkeyBean> data) {
        mAdapter = new HotKeyAdapter(this, data);
        mXrefreshView.stopRefresh();
        mXrefreshView.stopLoadMore();
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                String name = data.get(position).getName();
                if (!TextUtils.isEmpty(name)) {
                    mEtSearch.setText(name);
                    mEtSearch.setSelection(name.length());
                }
                getSearchResult();
                KeyboardUtils.hideSoftInput(SearchActivity.this);
            }
        });
        mXrefreshView.disallowInterceptTouchEvent(true);

    }


    @OnClick({R2.id.iv_back, R2.id.iv_search, R2.id.tv_clear_history})
    public void click(View view) {
        if (view.getId() == R.id.iv_back) {
            finish();
        }
        if (view.getId() == R.id.iv_search) {
            String history = mEtSearch.getText().toString();
            if (!TextUtils.isEmpty(history)) {
                if (!mHistoryMap.containsKey(history)) {
                    mHistoryMap.put(history, history);
                    PreferencesUtil.getInstance().saveParam("HistoryHashMap", mHistoryMap);
                    initHistoryData();
                }
                getSearchResult();
            }

        }
        if (view.getId() == R.id.tv_clear_history) {
            mHistoryMap.clear();
            PreferencesUtil.getInstance().saveParam("HistoryHashMap",mHistoryMap);
            initHistoryData();
            mFlowLayout.setVisibility(View.INVISIBLE);
        }
    }

    public void getSearchResult() {
        mTvHot.setVisibility(View.GONE);
        mLlHistory.setVisibility(View.GONE);
        mFlowLayout.setVisibility(View.GONE);
        mXrefreshView.disallowInterceptTouchEvent(false);
        mXrefreshView.startRefresh();
    }

    @Override
    public void showSearchResultSuccess(SearchResultBean bean, boolean isPullDown, boolean isSilence) {
        mXrefreshView.stopRefresh();
        mXrefreshView.stopLoadMore();
        page = bean.getCurPage();
        totalPage = bean.getPageCount();
        mResultAdapter = new SearchResultAdapter(this, bean.getDatas());
        mRecyclerView.setAdapter(mResultAdapter);
    }

}
